package yelmor.comm100.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by yel on 2016/5/7.
 */
@Controller
public class ImageController {
  /**
   * 通过url请求返回图像的字节流
   */
  @RequestMapping(path = "/sideImage/{picName}")
  public void getSideImage(@PathVariable("picName") String picName,
                      HttpServletRequest request,
                      HttpServletResponse response) throws IOException {

    String fileName = "/var/comm100/sideImage/" + picName;
    File file = new File(fileName);

    if (!(file.exists() && file.canRead())) {
      System.out.println("use default side image");
      fileName = "/var/comm100/sideImage/default.png";
      file = new File(fileName);
    } else {
      System.out.println("use custom image");
    }
    FileInputStream inputStream = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    int length = inputStream.read(data);
    inputStream.close();

    response.setContentType("image/png");

    OutputStream stream = response.getOutputStream();
    stream.write(data);
    stream.flush();
    stream.close();
  }

  @RequestMapping(path = "/logoImage/{picName}")
  public void getLogoImage(@PathVariable("picName") String picName,
                      HttpServletRequest request,
                      HttpServletResponse response) throws IOException {

    if (StringUtils.isEmpty(picName)) {
      picName = "";
    }
    String fileName = "/var/comm100/logoImage/" + picName;
    File file = new File(fileName);

    if (!(file.exists() && file.canRead())) {
      fileName = "/var/comm100/logoImage/default.png";
      file = new File(fileName);
    }
    FileInputStream inputStream = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    int length = inputStream.read(data);
    inputStream.close();

    response.setContentType("image/png");

    OutputStream stream = response.getOutputStream();
    stream.write(data);
    stream.flush();
    stream.close();
  }
}
